package com.maxlen.camunda.controller;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * webSocket服务端
 * 客户端本地测试可以使用这个网站: https://www.dute.org/websocket
 */
@ServerEndpoint("/webSocket/{uuid}")
@Component
public class WebSocketController {
    private final Logger logger = LoggerFactory.getLogger(WebSocketController.class);

    /**
     * 以 uuid 为 key，连接会话为对象保存起来
     */
    public static Map<String, Session> websocketClients = new ConcurrentHashMap<>();

    /**
     * 会话
     */
    private Session session;

    /**
     * 根据uuid唯一标识建立 websocket 通道
     */
    private String userId;

    /**
     * 发送消息到指定连接
     * @param userId 用户 ID
     * @param jsonString 消息
     */
    public static void sendMessage(String userId, String jsonString){
        Session nowSession = websocketClients.get(userId);
        if(nowSession!=null){
            try {
                nowSession.getBasicRemote().sendText(jsonString);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 连接建立成功
     * @param userId 用户 ID
     * @param session 会话
     */
    @OnOpen
    public void onOpen(@PathParam("uuid") String userId, Session session)
    {
        this.userId = userId;
        this.session = session;
        if(websocketClients.get(userId) == null){
            websocketClients.put(userId, session);
            logger.info("当前 {}：已创建连接", userId);
        }
    }


    /**
     * 连接错误
     * @param session 会话
     * @param error 错误信息
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("服务端发生了错误"+error.getMessage());
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose()
    {
        websocketClients.remove(userId);
        logger.info("当前 {}：已退出连接", userId);
    }

    /**
     * 接收客户端的消息
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session){
        logger.info("服务端从客户端 {} :收到了一条消息：{}", userId, message);
        //向客户端回传消息
        //session.getAsyncRemote().sendText("来自服务器："+uuid+"你的消息我收到啦");
    };

    /**
     * 向所有连接主动推送消息
     * @param jsonObject 消息体
     * @throws IOException
     */
    public static void sendMessageAll(JSONObject jsonObject) throws IOException {
        for (Session item : websocketClients.values()) {
            item.getAsyncRemote().sendText(jsonObject.toJSONString());
        }
    }
}
